import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpServe {
    private DatagramSocket socket=null;
    public UdpServe(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        //服务器不是只给一个客户端提供服务，需要服务很多客户端
        while(true) {
            //只要有客户端过来，就可以提供服务
            //1.读取客户端发来的请求是啥
            //receive方法的参数是一个输出型参数，需要先构造好个空白的DatagramPacket对象，交给receive来进行填充
            DatagramPacket requestPacket = new DatagramPacket(new byte[5000], 5000);
            socket.receive(requestPacket);
            //2.根据请求计算响应，由于此处是回显服务器，响应和请求相同
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //3.把响应写回到客户端，send的参数也是DatagramPacket需要把这个Packet对象构造好
             //此处构造的响应对象，不能是用空的字节数组构造了，而是使用响应数据来构造
            String response=process(request);
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //打印当前服务器ip和端口，请求和响应
            System.out.printf("[%s:%d] req:%s;resp:%s\n",requestPacket.getAddress().toString(),requestPacket.getPort(),request,
                    response);


        }
    }
    public String process(String request)
    {
        return request;

    }

    public static void main(String[] args) throws IOException {
        UdpServe serve=new UdpServe(9090);//端口号需要在1024-65535
        serve.start();
    }

}
